// 定义 mockFetch 相关函数
function mockFetch(url, options = {}) {
    const { delay = 1000 } = options;

    return new Promise((resolve, reject) => {
        setTimeout(() => handleRequest(resolve, reject, url, options), delay);
    });
}

function handleRequest(resolve, reject, url, options) {
    try {
        const response = createMockResponse(url, options.method);
        resolve(response);
    } catch (error) {
        reject(error);
    }
}

function createMockResponse(url, method = 'GET') {
    const responseData = {
        'https://api.example.com/data': { message: 'Hello, world!' },
        'https://api.example.com/post': { id: 1, status: 'created' },
    };

    if (!(url in responseData)) {
        throw new Error(`404 Not Found: ${url}`);
    }

    if (url === 'https://api.example.com/data' && method !== 'GET') {
        throw new Error(`405 Method Not Allowed: ${method}`);
    }

    return {
        ok: true,
        status: 200,
        json: () => Promise.resolve(responseData[url]),
        text: () => Promise.resolve(JSON.stringify(responseData[url])),
    };
}

// 测试 createMockResponse 函数
function testCreateMockResponse() {
    try {
        // 测试已知 URL 的 GET 请求
        const url1 = 'https://api.example.com/data';
        const response1 = createMockResponse(url1);
        console.assert(response1.ok === true, 'Response should be ok');
        console.assert(response1.status === 200, 'Response status should be 200');
        response1.json().then(data => {
            console.assert(JSON.stringify(data) === JSON.stringify({ message: 'Hello, world!' }), 'Response data should match');
        });

        // 测试未知 URL
        const url2 = 'https://api.example.com/unknown';
        try {
            createMockResponse(url2);
            console.assert(false, 'Should throw 404 error for unknown URL');
        } catch (error) {
            console.assert(error.message === '404 Not Found: https://api.example.com/unknown', 'Error message should match');
        }

        // 测试非 GET 方法在 data URL 上
        const url3 = 'https://api.example.com/data';
        const method = 'POST';
        try {
            createMockResponse(url3, method);
            console.assert(false, 'Should throw 405 error for non-GET method on data URL');
        } catch (error) {
            console.assert(error.message === '405 Method Not Allowed: POST', 'Error message should match');
        }

        console.log('createMockResponse() tests passed');
    } catch (error) {
        console.error('createMockResponse() tests failed:', error);
    }
}

// 测试 handleRequest 函数
function testHandleRequest() {
    try {
        // 测试已知 URL 的请求
        const url1 = 'https://api.example.com/data';
        const options1 = {};
        new Promise((resolve, reject) => {
            handleRequest(
                (response) => {
                    console.assert(response.ok === true, 'Response should be ok');
                    console.assert(response.status === 200, 'Response status should be 200');
                    resolve();
                },
                (error) => {
                    console.error('handleRequest should not reject for known URL:', error);
                    reject();
                },
                url1,
                options1
            );
        }).then(() => {
            // 测试未知 URL 的请求
            const url2 = 'https://api.example.com/unknown';
            const options2 = {};
            new Promise((resolve, reject) => {
                handleRequest(
                    () => {
                        console.error('handleRequest should reject for unknown URL');
                        reject();
                    },
                    (error) => {
                        console.assert(error.message === '404 Not Found: https://api.example.com/unknown', 'Error message should match');
                        resolve();
                    },
                    url2,
                    options2
                );
            }).then(() => {
                console.log('handleRequest tests passed');
            }).catch(error => {
                console.error('handleRequest tests failed:', error);
            });
        }).catch(error => {
            console.error('handleRequest tests failed:', error);
        });
    } catch (error) {
        console.error('handleRequest tests failed:', error);
    }
}

// 测试 mockFetch 函数
async function testMockFetch() {
    try {
        // 测试已知 URL 的请求
        const url1 = 'https://api.example.com/data';
        const options1 = { delay: 10 };
        const response1 = await mockFetch(url1, options1);

        // console.assert(condition, message);
        // condition：这是一个布尔表达式，是需要进行检查的条件。console.assert() 会对这个条件进行评估，如果条件为 true，表示断言通过，不会有任何额外的输出；如果条件为 false，则表示断言失败。
        // message：当断言失败时（即 condition 为 false），会在浏览器控制台或 Node.js 终端输出的错误信息。这个参数可以是一个字符串，也可以是其他可转换为字符串的类

        console.assert(response1.ok === true, 'Response should be ok');
        console.assert(response1.status === 200, 'Response status should be 200');
        const data1 = await response1.json();
        console.assert(JSON.stringify(data1) === JSON.stringify({ message: 'Hello, world!' }), 'Response data should match');

        // 测试未知 URL 的请求
        const url2 = 'https://api.example.com/unknown';
        const options2 = { delay: 10 };
        try {
            await mockFetch(url2, options2);
            console.assert(false, 'Should reject for unknown URL');
        } catch (error) {
            console.assert(error.message === '404 Not Found: https://api.example.com/unknown', 'Error message should match');
        }

        console.log('mockFetch tests passed');
    } catch (error) {
        console.error('mockFetch tests failed:', error);
    }
}

// 运行所有测试
testCreateMockResponse();
testHandleRequest();
testMockFetch()
    .then(() => {console.log('All mockFetch tests completed successfully.');})
    .catch(error => {console.error('mockFetch tests failed:', error);});